// pages/books/books.js
var that,
  api = new (require('../../utils/api.js')),
  imghead = api.getimgurl(),
  app = getApp(),
  util = new (require('../../utils/util.js'));

Page({
  /**
   * 页面的初始数据
   */
  data: {
    hasList: false,     // 列表是否有数据
    totalPrice: 0,      // 总价，初始为0
    selectAllStatus: true ,
    isall:!1,
    selectitems:[],
    totalcount:0,
    // cartids:[],
    totalprice:0,
    status:0,
    searchinput:"",
    getall: 0,
    switcharr: [],
  },
  formsubmit(e) {
    api.gatherformid(e, res => {

    })
  },
  tocheck(e) {
    let { index,id } = e.currentTarget.dataset, { list, goodslist,selectitems, totalcount,isall,ids,cartids } = this.data,issel=!1;
    goodslist.forEach(x=>{
      if(x.check==1){
        issel=!0;
      }
    })
    if(issel){
      wx.showToast({
        title: '绘本借阅能和其它商品一起选中',
        icon: 'none'
      })
      return;
    }
    if (list[index]['check']==0){
      list[index]['check'] = 1;
      totalcount++;
      cartids.push(id);
    
    }else{
      list[index]['check'] = 0;
      cartids.splice(index,1);
     
      totalcount--
    }
    if(totalcount==list.length){
      isall = 1;
    }else{
      isall = 0;
    }
    this.setData({ list, selectitems, totalcount,isall,cartids});
    wx.setStorageSync("cartids",cartids);
  },
  toconfirm() {
    let userinfo = wx.getStorageSync('userinfo'), { origuserinfo,totalnumber}=this.data
    if (totalnumber<=0){
      wx.showModal({
        title: '提示',
        content: '还没有选中任何商品哦~',
        showCancel: !1
      })
      return;
    }
    // if (!origuserinfo) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '请先登录，再提交订单',
    //     showCancel: false,
    //     success: function(res) {
    //       if (res.confirm) {
    //         wx.redirectTo({
    //           url: '../empower/empower',
    //         })
    //       }
    //     }
    //   })
    //   return;
    // }
    var {
      switcharr, list,address
    } = this.data, goodssn = [], goodscount=[],cartids = [];
    switcharr.forEach(x=>{
      list.forEach(y=>{
        if(x=y.goodsid){
          // goodssn.push(y['goodsnum'])
          goodscount.push(y['paynum'])
          cartids.push(y.goodsid)
        }
      })
      
    })
    that.setData({addorderdata:{ goodssn: goodssn.join(','), goodscount: goodscount.join(','), cartids: cartids.join(',')}},()=>{
      wx.navigateTo({
              url: '../confirm/confirm?total='+that.data.total,
            })
    })
  },
  jumptogoodsdetail(e){
    let { id } = e.currentTarget.dataset;
    console.log(e, 'idid')
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?id=' + id,
    })
  },   
  getsettting(){
      api.getsetting(res => {
        if (res.data.issuccess == 1) {
          let setting = res.data.data,
          maxborrow = setting.maxborrow;
          wx.setStorageSync("setting", setting);
          this.setData({ maxborrow });
        }
      });
  },
  todo(){
   
  },
search(e){
  let searchinput = e.detail.value,totalcount=0,
  { list } = this.data;
  if (searchinput == "") {
    this.getlist();
  } else {
    let alist = [];
    list.forEach((x, i) => {
      console.log(x.name.indexOf("分"),searchinput,e);
      if (x.name.indexOf(searchinput) != -1) {
        alist.push(x);
        if(x.check==1){
          totalcount++;
        }
      }
    });
   app.badege(alist);
    this.setData({ list:alist,totalcount });
  }
},
tosearch(){

},
 edit(){
  let {status} = this.data;
  status=status==0?1:0;
  console.log(status,"status");
  this.setData({status});
 },
  todetail(e){
    let {id} = e.currentTarget.dataset;
    console.log(id,e);
    wx.navigateTo({
      url: '../books/detail/detail?i='+id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('omload')
    that = this;
    this.getsettting();
  },

  getdata(){
    api.getcarts(res=>{
      if(res.data.issuccess==1){
        let list = res.data.list;
        this.formatdata(list);
        that.setData({list})
      }
    })
    api.getcargoodslist( res => {
      if (res.data.issuccess == 1) {
        // let cartids = res.data.list.concat(that.data.list)
        //   wx.setStorageSync('cartids', cartids) 
        //   app.badege(cartids)
        let goodslist =[]
        if(res.data.list.length>0){
          res.data.list.forEach((x, i) => {
            x.check=0;
            x['newprice']=(x.promotionprice/100).toFixed(2)
            x.thumbPicPath = imghead + x.thumbPicPath;
            // x.newprom=(x.promotionprice/100).toFixed(2)
            goodslist.push(x)
          })
        }   
    that.setData({ goodslist,isload:!0 },()=>{
     
    })
      }
    })
   
  },
  formatdata(list){
    list.forEach((x,i)=>{
      list[i]['check'] = 0
      if(x.thumbPicPath.indexOf("http")){
        x.thumbPicPath = imghead + x.thumbPicPath;
      }
    });
    
    this.setData({list});
    // this.selectcheck();
  },

  deleteList(e){
    console.log(e,'eee')
    let { list, totalcount,cartids } = this.data, { index,ids } = e.currentTarget.dataset,
    {type} = e.target.dataset;
    if(type==1){
      ids=cartids;
    }
    wx.showModal({
      title: '提示',
      content: '确认删除吗',
      success:function(res){
        if(res.confirm){
          api.delcart({ids}, res => {
            if (res.data.issuccess == 1) {
              if(type==1){
                totalcount = totalcount - cartids.length;
                for (let i = list.length - 1; i >= 0; i--) {
                  for(let j = cartids.length-1;j>=0;j--){
                    if (list[i].goodsid == cartids[j]) {
                      list.splice(i, 1);
                      break;
                    }
                  }
                }
                // app.badege(list);
                cartids = [];
              }else{
                if (list[index]['check'] == 1) {
                  totalcount--;
                }
                list.splice(index, 1);
                cartids.splice(index, 1);         
              }
              wx.showToast({
                title: '删除成功',
              })
              wx.setStorageSync("cartids", cartids);
              app.badege(cartids);
              that.setData({ cartids, list, totalcount});
            }
          });
        }

      }
    })
    
  },

  delcart(){
    let {switcharr}=that.data
    if(switcharr.length==0){
        wx.showToast({
          title: '您还没选择需要删除的商品',
          icon: 'none'
        })
        return;
    }else{
      let ids=switcharr.toString()
      wx.showModal({
        title: '删除商品',
        content: '确认删除吗？',
        success: function(res) {
          if (res.confirm) {
            api.delcart({ids}, res => {
              if (res.data.issuccess == 1) {
                console.log(res.data.list,'res.data.listres.data.list');
                let cartids=wx.getStorageSync("cartids");
                switcharr.forEach((x,i)=>{
                  cartids.forEach((y,j)=>{
                    if(y==x){
                      cartids.splice(j,1)
                    }
                  })
                })
                wx.setStorageSync("cartids", cartids);
                app.badege(cartids);
                that.getlist(res.data.list)
                that.setData({switcharr:[],isedit:!1})
              }
            });
          }
        },
      })
    }
  },
  // selectcheck(){
  //   let { list, isall,goodslist } = this.data, cartids = [],totalcount=0
  //   list.map((x, i) => {
  //     if (x.kc > 0) {
  //       cartids.push(list[i].goodsid);
  //       list[i]['check'] = 1;
  //       totalcount++;
  //     }
  //   })
  //   wx.setStorageSync("cartids", cartids);
  //   this.setData({ totalcount, list, isall: !0, cartids })
  // },
  selectall(){
    let { list, isall,goodslist } = this.data, check = isall ? 0 : 1,cartids=[],totalcount=0,issel=!1;
    goodslist.forEach(x=>{
      if(x.check==1){
        issel=!0;
      }
    })
    if(issel){
      wx.showToast({
        title: '优选购商品不能和其它商品一起选择',
        icon: 'none'
      })
      return;
    }
    list.map((x,i)=>{
      if(x.kc>0){
        cartids.push(list[i].goodsid);
        list[i]['check'] = check;
        totalcount++;
      }
    })
    this.setData({ totalcount: isall?0:totalcount, list, isall: !isall,cartids:isall?[]:cartids})
  },
  toorder(){
    let { totalcount, cartids, maxborrow,list} = this.data,
    payids = [];
    list.forEach((x,i)=>{
      if(x.check==1){
        payids.push(x.goodsid);
      }
    });
    wx.setStorageSync("payids", payids);
    if(maxborrow<totalcount){
      wx.showToast({
        icon:'none',
        title: '借阅最大数为'+maxborrow,
      })
      return;
    }
    if(Number(totalcount)==0){
      wx.showToast({
        title: '您未选择任何图书',
        icon:'none'
      })
      return;
    }
    // wx.requestSubscribeMessage({
    //   tmplIds: ['RxoJIrjvpTBHGObvr2AhXnRE9H-ABO1QhM6PTVOqPwM'],
    //   success: (res) => {
    //     console.log('订阅结果');
    //     console.log(res);
    //     if (res.errMsg == 'requestSubscribeMessage:ok') {
    //       let status = res['RxoJIrjvpTBHGObvr2AhXnRE9H-ABO1QhM6PTVOqPwM'];
    //       console.log(status);
    //     } else {
    //       wx.showModal({
    //         showCancel: false,
    //         title: '提示',
    //         message: res.errMsg + ',请重新订阅！'
    //       })
    //     }
    //   },
    //   fail: ex => {
    //     wx.showModal({
    //       title: '提示',
    //       message: JSON.stringify(ex),
    //       showCancel: false
    //     })
    //   }
    // })
    wx.navigateTo({
      url: '../pay/pay',
    })
  },
  getlist(orderlist) {
    console.log('deldeldeldledldele');
    
    var show_totalcount = '',
      totalcount = 0, totalnumber=0,{switcharr,goodslist} = this.data;
    // if (orderlist.length > 0) {
      orderlist.map((x, i) => {
        x.thumbPicPath = imghead + x.thumbPicPath;
        orderlist[i]['check'] = switcharr.indexOf(i)>-1?1:0
        orderlist[i]['newprice']=(x.promotionprice/100).toFixed(2)
        totalcount += Number(orderlist[i]['promotionprice']) * x.goodscount
        show_totalcount = (totalcount / 100).toFixed(2)
      })
      // console.log("isbuy", isbuy); 
      that.setData({
        nolist: !1,
        goodslist: orderlist,
        totalcount,
        show_totalcount,
        getall: (switcharr.length==orderlist.length&&switcharr.length!=0)?1:0
      })
    // }
    this.counttotal();
  },
  getall() {
    var {getall, goodslist,list} = this.data,issel=!1;
    list.forEach(x=>{
      if(x.check==1){
        issel=!0;
      }
    })
    if(issel){
      wx.showToast({
        title: '优选购商品不能和其它商品一起选择',
        icon: 'none'
      })
      return;
    }
    getall = getall == 1 ? 0 : 1;
    goodslist.map((x, i) => {
      goodslist[i]['check'] = getall
    })
    this.setData({
      goodslist,
      getall
    }, () => {
      this.counttotal()
    });
  },
  switchtap(e) {
    let {check,index} = e.currentTarget.dataset,{goodslist,switcharr,list} = this.data,issel=!1;
    list.forEach(x=>{
      if(x.check==1){
        issel=!0;
      }
    })
    if(issel){
      wx.showToast({
        title: '优选购商品不能和其它商品一起选择',
        icon: 'none'
      })
      return;
    }
    console.log(check, 'check')
    goodslist[index].check = check == 0 ? 1 : 0
    this.counttotal();
    this.setData({
      goodslist,
      getall: 0
    })
  },
  counttap(e) {
    //totalnumber  共计数
    //show_totalcount 总计金额
    let { code, item,index } = e.currentTarget.dataset
    if( code == 0 &&Number(item.paynum) == 1){
      console.log(item,'itemitemitem');
      let {id,goodsid} = item
      console.log(id,'iddididiid');
      api.delcart({ids:goodsid}, res => {
        if (res.data.issuccess == 1) {
          let cartids = wx.getStorageSync("cartids");
          cartids.splice(index, 1)
          wx.setStorageSync("cartids", cartids);
          app.badege(cartids);
          that.getlist(res.data.list)
        }
      });
    }else{
      api.setCartcount({ id: item.id, count: code == 0 ? Number(item.paynum) - 1 : Number(item.paynum) + 1},res=>{
        if(res.data.issuccess==1){
          //处理list
          that.getlist(res.data.list)
        }
      })
    }
  },
  //计算总价
  counttotal() {
    console.log(22222222);
    
    var { goodslist } = this.data, total = 0, switcharr = [], totalnumber = 0, show_totalcount = 0;
    goodslist.forEach((x, i) => {
      if (x.check == 1) {
        switcharr.push(x.goodsid)
        total += Number(x.promotionprice) * Number(x.paynum);
        totalnumber += Number(x.goodscount)
      }
    })
    show_totalcount = (total / 100).toFixed(2);
    this.setData({
      total,
      switcharr,
      totalnumber,
      show_totalcount
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onshow')
    this.setData({status:!1,isall:!1,getall:0,cartids:[],switcharr:[]});
    let cartids=wx.getStorageSync("cartids");
    app.badege(cartids);
    this.getdata();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('onhide')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('onunload')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.logininfo.appletname,
      path: `pages/listen/listen?share=`+app.logininfo.userid,
    }
  }
})